import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Switch, Icon, Input, Select, Button, Row, Col, message } from 'antd'
import httpFetch from 'share/httpFetch'
import menuRoute from 'routes/menuRoute'
import config from 'config'
import { LanguageInput } from 'components/template';

const FormItem = Form.Item;
const Option = Select.Option;

class NewBudgetJournalType extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      budgetJournalTypeDetailPage: menuRoute.getRouteItem('budget-journal-type-detail','key'),    //项目组详情的页面项
      budgetOrganization: menuRoute.getRouteItem('budget-organization-detail', 'key'),  //预算组织详情的页面项
      loading: false,
      businessTypeOptions: [],
      i18n: {}
    };
  }

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({ loading: true });
        values.organizationId = this.props.organization.id;
        values.i18n = this.state.i18n;
        httpFetch.post(`${config.budgetUrl}/api/budget/journal/types`, values)
          .then((res) => {
            message.success(`${messages('budget-setting.key110'/*预算日记账*/)}${messages('common.create.success', { name: res.data.journalTypeName })}`);
            this.context.router.replace(this.state.budgetJournalTypeDetailPage.url.replace(':typeId', res.data.id)
              .replace(':id', this.props.organization.id));
          })
          .catch((e) => {
            if (e.response) {
              message.error(`${messages('common.save.filed')} , ${e.response.data.validationErrors ? e.response.data.validationErrors[0].message : e.response.data.message}`);
            }
          })
          .finally(() => {
            this.setState({ loading: false });
          });
      }
    });
  };

  componentWillMount(){
    this.getSystemValueList(2018).then(res => {
      this.setState({ businessTypeOptions: res.data.values })
    })
  }


  handleI18n = (name, value) => {
    let { i18n, journalTypeName } = this.state;
    i18n.journalTypeName = value;
    journalTypeName = name;
    this.setState({ journalTypeName, i18n });
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    const { loading, journalTypeName, i18n } = this.state;
    return (
      <div onSubmit={this.handleSave}>
        <h3 className="header-title">{messages('budget-setting.key111'/*新建预算日记账类型*/)}{/*新建预算日记账类型*/}</h3>
        <div className="common-top-area">
          <Form>
            <Row gutter={40}>
              <Col span={8}>
                <FormItem label={messages('budget-setting.key47'/*预算组织*/)}>
                  {getFieldDecorator("organizationName", {
                    initialValue: this.props.organization.organizationName
                  })(
                    <Input disabled />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label={messages('budget-setting.key99'/*预算日记账类型代码*/)}>
                  {getFieldDecorator("journalTypeCode", {
                    rules: [{
                      required: true,
                      message: messages('common.please.enter'),  //请输入
                    }],
                    initialValue: ''
                  })(
                    <Input />
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label={messages('budget-setting.key100'/*预算日记账类型名称*/)}>
                  {getFieldDecorator("journalTypeName", {
                    rules: [{
                      required: true,
                      message: messages('common.please.enter'),  //请输入
                    }],
                    initialValue: ''
                  })(
                    <LanguageInput
                      name={journalTypeName}
                      i18nName={i18n.journalTypeName || null}
                      nameChange={this.handleI18n}
                      placeholder={messages('common.please.enter')/* 请输入 */}/>                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={40}>
              <Col span={8}>
                <FormItem label={messages('budget-setting.key101'/*预算业务类型*/)}>
                  {getFieldDecorator("businessType", {
                    rules: [{
                      required: true,
                      message: messages('common.please.select'),  //请选择
                    }],
                    initialValue: ''
                  })(
                    <Select placeholder={messages('common.please.select')} getPopupContainer={triggerNode => triggerNode.parentNode}>
                      {this.state.businessTypeOptions.map((option)=>{
                        return <Option key={option.code}>{option.messageKey}</Option>
                      })}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem label={messages('common.column.status')}>
                  {getFieldDecorator('isEnabled', {
                    initialValue: true
                  })(
                    <Switch defaultChecked={true} checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="cross" />}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <Button htmlType="submit" type="primary" loading={loading}>{messages('common.save')/*保存*/}</Button>
                <Button style={{ marginLeft: 8 }} onClick={() => {this.context.router.push(this.state.budgetOrganization.url.replace(":id", this.props.organization.id) + '?tab=JOURNAL_TYPE');}}>{messages('common.cancel')/*取消*/}</Button>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    organization: state.budget.organization
  }
}

NewBudgetJournalType.contextTypes = {
  router: React.PropTypes.object
};

const WrappedNewBudgetJournalType = Form.create()(NewBudgetJournalType);

export default connect(mapStateToProps)(WrappedNewBudgetJournalType);
